#include "text.h"
void scrCatInt(char *scrbuf,int catInt) {
	char buf[10];
	sprintf(buf,"%d",catInt);
	strcat(scrbuf,buf);
}
void scrCatStrInt(char *scrbuf,char *catBuf,int catInt) {
	char buf[20];
	sprintf(buf,"%s%d",catBuf,catInt);

	strcat(scrbuf,buf);
}
void scrBufCatBack(int type) {
	if(type==0)return;
	_ScreenIndex++;
	if(_ScreenIndex == 1)return;
	for(int i=0; i<W*H; i++) {
		if(strncmp(scrBuf+i,scrBufBack+i,1) == 0)
			continue;
		if(type = 2) {
			if(isgraph(*(scrBuf+i)) || strcmp((scrBuf+i),"|")==0)
				continue;
		} else {
			if(strcmp((scrBuf+i),"|")==0 || strcmp((scrBuf+i),P1)==0 || strcmp((scrBuf+i),SP)==0)
				continue;
		}

		strcpy(scrBuf+i,scrBufBack+i);

	}
	memset(scrBufBack,'\0',sizeof(scrBufBack));
}

void showStr(char *destBuf,struct V2s v2s,const char *str,int isWithBack) {

	int len = strlen(str);
	for(int i=0; i<v2s.y; i++) {
		for(int j=0; j<W; j++) {
			if(j==0) scrCatInt(destBuf,i%10);
			else if(j==W-1 &&i!=0) strcat(destBuf,WallH);
			else if(i==0) scrCatInt(destBuf,j%10);
			else strcat(destBuf,SP);
		}
		strcat(destBuf,RT);
	}

	for(int j=0; j<v2s.x; j++) {
		if(j==0) scrCatInt(destBuf,(v2s.y)%10);
		else strcat(destBuf,SP);
	}

	strcat(destBuf,str);
	for(int j=v2s.x+len; j<W; j++) {
		if(j==W-1) strcat(destBuf,WallH);
		else strcat(destBuf,SP);
	}
	strcat(destBuf,RT);



	for(int i=v2s.y+1; i<H; i++) {
		for(int j=0; j<W; j++) {
			if(j==0) scrCatInt(destBuf,i%10);
			else if(j==W-1) strcat(destBuf,WallH);
			else strcat(destBuf,SP);
		}
		strcat(destBuf,RT);
	}

	for(int j=0; j<W; j++)
		strcat(destBuf,WallW);
	//show console
//	char console[30];
//	sprintf(console,"\nlogo(x:%d,y:%d)",v2s.x,v2s.y);
	//printf("\nlogo(x:%d,y:%d)",v2s.x,v2s.y);
//	strcat(destBuf,console);
	//printf("\n%s",destBuf);
	//strcat(destBuf,RT);

	scrBufCatBack(isWithBack);
	clrscr();
	printf("%s",scrBuf);
}
void txtClear() {
	_ScreenIndex = 0;
	memset(scrBuf,'\0',sizeof(scrBuf));
}
int showTxt(struct V2s v2s,const char *str) {
	if(_ScreenIndex==0)
		showStr(scrBuf,v2s, str,2);
	else
		showStr(scrBufBack,v2s, str,2);
	return _ScreenIndex;
}
void showMapRect() {
	struct V2s v2s= {.x=1,.y=1};
	showTxt(v2s,SP);
}

void showMenu(int pos,const char *str) {
	enum MenuPos menuPos;
	int len = strlen(str);
	struct V2s v2s_top = {
		.x=(W-len+1)/2,.y=1
	};
	struct V2s v2s_center = {
		.x=(W-len+1)/2,.y=(H+1)/2
	};
	struct V2s v2s_top_center = {
		.x=(W-len+1)/2,.y=(H+1)/2-2
	};
	struct V2s v2s_bottom_center = {
		.x=(W-len+1)/2,.y=(H+1)/2+2
	};
	struct V2s v2s_bottom = {
		.x=(W-len+1)/2,.y=H-1
	};
	switch(pos) {
		case top:
			gotoxy(v2s_top.x,v2s_top.y);
			break;
		case top_center:
			gotoxy(v2s_top_center.x,v2s_top_center.y);


			break;

		case center:
			gotoxy(v2s_center.x,v2s_center.y);

			break;
		case bottom_center:
			gotoxy(v2s_bottom_center.x,v2s_bottom_center.y);

			break;
		case bottom:
			gotoxy(v2s_bottom.x,v2s_bottom.y);

			break;

	}
	printf(str);

}
